package com.example.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.config.IsAuth;
import com.example.config.ServiceDiscoveryService;
import com.example.feign.ProviderFeign;
import com.example.utils.Results;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;
import java.util.Optional;


@RestController
@RequestMapping("/test")
public class ApiController {

    @Autowired
    @Qualifier("loadBalancedRestTemplate")
    private RestTemplate restTemplate;

    private static final String PROVIDER_SERVICE = "cloud-provider";

    @Autowired
    private ProviderFeign providerFeign;

    @Autowired
    private ServiceDiscoveryService serviceDiscoveryService;

    @ApiOperation("测试示例")
    @GetMapping("/test")
    public JSONObject testController(){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg", "hello world");
        jsonObject.put("code", 200);
        return jsonObject;
    }

    @ApiOperation("feign调用")
    @GetMapping("/feign")
    public JSONObject feignController(){
        JSONObject object=providerFeign.proApi();
        return object;
    }


    @ApiOperation("服务实例获取通过服务名")
    @GetMapping("/instanceslist")
    public JSONObject instancesController(@RequestParam("serviceName")String serviceName){
        if(!StringUtils.hasText(serviceName)){
            return Results.error("服务名不得为空");
        }
        List<Map<String,Object>> mapList=serviceDiscoveryService.getServiceInstancesDetail(serviceName);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("serviceName",serviceName);
        jsonObject.put("size",mapList==null ? 0 : mapList.size());
        jsonObject.put("data",mapList);
        return Results.success(jsonObject);
    }

    @ApiOperation("loadbanlace 负载均衡")
    @GetMapping("/loadbalance")
    public JSONObject loadBalanceController(){
        String url = "http://" + PROVIDER_SERVICE + "/pro/api";
        ResponseEntity<Map> response=restTemplate.exchange(url,HttpMethod.GET,null,Map.class, Optional.ofNullable(""));
        return Results.success(response.getBody());
    }


    @IsAuth(isSecurity = false)
    @ApiOperation("匿名使用测试")
    @GetMapping("noauth")
    public JSONObject noAuthController(){
        return Results.success("no auth ~~");
    }


}
